import axios from 'axios'

// const baseURL = 'http://172.16.43.24:8085/'
const baseURL_PRO = 'https://meikou-api.itheima.net/'
export const ORDER_TOKEN = 'order_token'

const request = axios.create({
  baseURL: baseURL_PRO,
  timeout: 100000,
})

// 添加请求拦截器
request.interceptors.request.use((config) => {
  const token = localStorage.getItem(ORDER_TOKEN)
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export interface LoginForm {
  account: string
  password: string
}

// 登录
export const loginAPI = (data: LoginForm) => {
  return request({
    url: '/login',
    method: 'POST',
    data,
  })
}

// 订单状态
/**
 * 订单状态，1为待付款、2为待发货、3为待收货、4为待评价、5为已完成、6为已取消
 */

export type OrderState = 1 | 2 | 3 | 4 | 5 | 6

export interface Request {
  orderState?: OrderState
  page?: number
  pageSize?: number
}

// 订单
export const getOrderAPI = (reqParams: Request) => {
  return request({
    url: '/member/order',
    params: reqParams,
  })
}

export interface UpdateStatusReq {
  orderId: string
  payState?: number
  orderState?: OrderState
}

// 恢复为已支付待发货
export const updateOrderStatusAPI = (reqParams: UpdateStatusReq) => {
  const { orderId, payState = 2, orderState = 2 } = reqParams
  return request({
    url: '/member/order/updateStatus',
    method: 'PUT',
    params: {
      orderId,
      payState,
      orderState,
    },
  })
}

// 发货
export const consignmentAPI = (id: string) => {
  return request({
    url: `/member/order/consignment/${id}`,
  })
}
